<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.keywords" placeholder="请输入搜索内容" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button v-waves class="filter-item" type="primary" @click="addAdmin">新增</el-button>
    </div>

    <!--表格开始-->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" width="120px" align="center">
        <template slot-scope="scope">
          <el-tag>{{ scope.row.id }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="180px" align="center">
        <template slot-scope="scope">
          <el-switch
            :value="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="changes(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="添加时间" width="250px" align="center">
        <template slot-scope="scope">
          <el-tag>{{ renderTime(scope.row.createdAt) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="账号" width="220px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="权限" min-width="100px" align="center">
        <template slot-scope="scope">
          <el-tag type="success">{{ scope.row.role.remake }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="角色" min-width="100px" align="center">
        <template slot-scope="scope">
          <el-select v-model="scope.row.role_id" placeholder="请选择" @change="editRoles(scope.row)">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.remake"
              :value="item.id"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="100px" align="center">
        <template slot-scope="scope">
          <el-button type="danger" size="mini" @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog
      title="新增管理员"
      :visible.sync="dialogVisible"
      width="40%"
      :before-close="Close"
    >
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="账号">
          <el-input v-model="form.username" style="width: 70%;" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="form.password" type="password" style="width: 70%;" />
        </el-form-item>
        <el-form-item label="重复密码">
          <el-input v-model="form.lastPassword" type="password" style="width: 70%;" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="form.role_id" placeholder="请选择">
            <el-option
              v-for="item in roles"
              :key="item.id"
              :label="item.remake"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">立即创建</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import { getList, freeze, editRole, delAdmin, addAdmin } from '@/api/admin'
import { roles } from '@/api/roles'
import { renderTime } from '../../utils'
export default {
  name: 'Admins',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      collection: '',
      listLoading: false,
      dialogVisible: false,
      listQuery: {
        page: 1,
        limit: 10,
        keywords: undefined
      },
      id: undefined,
      roles: [],
      form: {
        username: '',
        password: '',
        lastPassword: '',
        role_id: ''
      }
    }
  },
  created() {
    this.getList()
    this.getRoles()
  },
  methods: {
    renderTime,
    // 获取数据
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(res => {
        const { data: { count, rows }} = res.data
        this.total = count
        this.list = rows
        setTimeout(() => {
          this.listLoading = false
        }, 500)
      }).catch(err => {
        console.log(err)
      })
    },
    // 分页
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 新增
    addAdmin() {
      this.dialogVisible = true
    },
    // 删除
    del(id) {
      if (id === 1) {
        this.$message({
          type: 'error',
          message: '不能删除超级管理员'
        })
        return false
      }
      this.$confirm('此操作将删除该管理员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delAdmin(id)
          .then(res => {
            const { msg } = res.data
            this.$message({
              type: 'success',
              message: msg
            })
            this.getList()
          })
          .catch(err => {
            console.log(err)
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // 禁用、启用管理员
    changes(row) {
      if (row.id === 1) {
        this.$message({
          type: 'error',
          message: '不能操作超级管理员'
        })
        return false
      }
      const status = this.list.filter(item => item.id === row.id)[0].status
      this.list.filter(item => item.id === row.id)[0].status = !status
      this.$confirm('此操作将改变该管理员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        freeze(row.id, row.status)
          .then(res => {
            const { msg } = res.data
            this.$message({
              type: 'success',
              message: msg
            })
            this.getList()
          })
          .catch(err => {
            console.log(err)
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
        this.list.filter(item => item.id === row.id)[0].status = status
      })
    },
    // 更改角色
    editRoles(row) {
      if (row.id === 1) {
        this.$message({
          type: 'error',
          message: '不能操作超级管理员'
        })
        return false
      }
      const data = { id: row.id, roleId: row.role_id }
      this.$confirm('此操作将改变该管理员角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        editRole(data)
          .then(res => {
            const { msg } = res.data
            this.$message({
              type: 'success',
              message: msg
            })
            this.getList()
          })
          .catch(err => {
            console.log(err)
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    // onSubmit
    onSubmit() {
      // 粗糙的验证
      const myReg = /^[a-zA-Z0-9_]*$/
      const data = this.form
      if (!data.username) {
        this.msg('账号不能为空')
        return
      }
      // 粗糙的验证是否含有中文
      if (!myReg.test(data.username)) {
        this.msg('账号不能还有特殊字符和中文')
        return
      }
      // 粗糙的验证是否有密码
      if (!data.password) {
        this.msg('请输入密码')
        return
      }
      // 粗糙的验证密码
      if (!data.lastPassword) {
        this.msg('请再次输入密码')
        return
      }
      // 粗糙的验证密码
      if (data.lastPassword !== data.password) {
        this.msg('两次密码不一致')
        return
      }
      // 粗糙的验证
      if (!data.role_id) {
        this.msg('请选择角色')
        return
      }
      // console.log(this.form)
      const r = { username: data.username, password: data.lastPassword, roleId: data.role_id }
      addAdmin(r).then(res => {
        const { msg } = res.data
        this.$message({
          type: 'success',
          message: msg
        })
        this.dialogVisible = false
        this.form = { username: '', password: '', lastPassword: '', role_id: '' }
        this.getList()
      }).catch(() => {})
    },
    // 获取角色
    getRoles() {
      roles().then(res => {
        const { data } = res.data
        this.roles = data.rows
      }).catch(err => {
        console.log(err)
      })
    },
    Close() {
      this.form = { username: '', password: '', lastPassword: '', role_id: '' }
      this.dialogVisible = false
    },
    msg(msg) {
      this.$message({
        type: 'error',
        message: msg
      })
    }
  }
}
</script>
<style></style>
